"""
数据清洗工具函数
"""
import re
import pandas as pd
from html import unescape


def clean_salary(salary_str):
    """
    清洗薪资数据
    
    输入：
        "25k-40k" → (25.0, 40.0, 32.5)
        "15-30k"  → (15.0, 30.0, 22.5)
        "25-45k·15薪" → (25.0, 45.0, 35.0, 15)
        "面议"     → (None, None, None, None)
        None       → (None, None, None, None)
    
    返回：
        (salary_min, salary_max, salary_avg, salary_months)
    """
    if pd.isna(salary_str) or not salary_str:
        return None, None, None, None
    
    salary_str = str(salary_str)
    
    # 提取薪资月数（如"15薪"）
    months_match = re.search(r'·(\d+)薪', salary_str)
    salary_months = int(months_match.group(1)) if months_match else None
    
    # 标准格式："25k-40k" 或 "25-40k"
    match = re.search(r'(\d+\.?\d*)k?-(\d+\.?\d*)k', salary_str, re.IGNORECASE)
    
    if match:
        salary_min = float(match.group(1))
        salary_max = float(match.group(2))
        salary_avg = (salary_min + salary_max) / 2
        return salary_min, salary_max, salary_avg, salary_months
    
    # 单个数字："30k以上"
    match = re.search(r'(\d+\.?\d*)k', salary_str, re.IGNORECASE)
    if match:
        salary = float(match.group(1))
        return salary, salary, salary, salary_months
    
    # 其他情况（面议等）
    return None, None, None, salary_months


def clean_html(text):
    """
    清理HTML标签
    
    输入：
        "<br />1、负责..." → "1、负责..."
        "<p>岗位职责:</p>" → "岗位职责:"
    
    返回：
        清理后的纯文本
    """
    if pd.isna(text):
        return None
    
    text = str(text)
    
    # 1. HTML实体解码（&nbsp; → 空格）
    text = unescape(text)
    
    # 2. 移除所有HTML标签
    text = re.sub(r'<[^>]+>', '', text)
    
    # 3. 替换多个空格/换行为单个空格
    text = re.sub(r'\s+', ' ', text)
    
    # 4. 去除首尾空白
    text = text.strip()
    
    return text if text else None


def clean_text_field(text):
    """
    清理普通文本字段
    
    - 去除首尾空白
    - 替换多个空格为单个
    """
    if pd.isna(text):
        return None
    
    text = str(text).strip()
    text = re.sub(r'\s+', ' ', text)
    
    return text if text else None


def split_location(location_str):
    """
    拆分地点字段
    
    输入：
        "北京"      → ("北京", None)
        "北京-朝阳区" → ("北京", "朝阳区")
    
    返回：
        (city, district)
    """
    if pd.isna(location_str) or not location_str:
        return None, None
    
    location_str = str(location_str).strip()
    
    if '-' in location_str:
        parts = location_str.split('-', 1)
        return parts[0].strip(), parts[1].strip()
    else:
        return location_str, None


def normalize_education(education_str):
    """
    规范化学历要求
    
    输入：
        "统招本科" → "本科"
        "学历不限" → "不限"
    
    返回：
        规范化的学历字符串
    """
    if pd.isna(education_str) or not education_str:
        return None
    
    education_str = str(education_str).strip()
    
    # 映射规则
    education_map = {
        '统招本科': '本科',
        '学历不限': '不限',
        '经验不限': '不限',
        '大专及以上': '大专',
        '本科及以上': '本科',
        '硕士及以上': '硕士',
    }
    
    return education_map.get(education_str, education_str)


def validate_salary(salary_min, salary_max):
    """
    验证薪资数据合理性
    
    Args:
        salary_min: 最低薪资
        salary_max: 最高薪资
    
    Returns:
        bool: 是否合理
    """
    if salary_min is None or salary_max is None:
        return True  # 空值视为合理
    
    # 薪资范围：3k-200k
    if salary_min < 3 or salary_max > 200:
        return False
    
    # 最低薪资不能大于最高薪资
    if salary_min > salary_max:
        return False
    
    return True

